package com.jianzh5.action.admin;

import com.jianzh5.action.BaseAction;
import com.jianzh5.common.DataPage;
import com.jianzh5.common.DataTables;
import com.jianzh5.common.ResultJson;
import com.jianzh5.pojo.PAdmin;
import com.jianzh5.pojo.PProduct;
import com.jianzh5.service.ProductServiceI;
import com.jianzh5.util.FileUploadUtils;
import com.jianzh5.util.InfoCenterHome;
import com.jianzh5.util.UserUtils;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

@Controller
@RequestMapping("/product/product")
public class ProductAction extends BaseAction {
    @Autowired
    private ProductServiceI productService;

    @RequestMapping(value = "/productList" ,method = RequestMethod.GET)
    @RequiresPermissions("product:product:view")
    public String productList(){
        return InfoCenterHome.SERVLET_ADMIN_ROOT+"product/productList";
    }

    @RequestMapping(value = "/productList",method = RequestMethod.POST)
    @ResponseBody
    public DataTables productList(DataPage dataPage ,HttpServletRequest request){
        String sindex = request.getParameter("order[0][column]");
        String order = request.getParameter("order[0][dir]");
        String sort = request.getParameter("columns["+sindex+"][data]");
        DataTables dt = productService.dataTables(order,sort,dataPage);
        return dt;
    }

    @RequestMapping("/editProduct")
    @RequiresPermissions("product:product:edit")
    public String editProduct(PProduct product,Model model){
        model.addAttribute("productCategory",productService.productCategory());
        if(product.getId() != 0){
            //编辑，需加载游戏信息
            product = productService.getProduct(product.getId());
            model.addAttribute("product",product);
        }
        return InfoCenterHome.SERVLET_ADMIN_ROOT+"product/productEdit";
    }

    @RequestMapping("/productEdit")
    @ResponseBody
    public ResultJson productEdit(PProduct product, HttpServletRequest request){
        PAdmin pAdmin = UserUtils.getUser();
        ResultJson json = new ResultJson();
        try {
            product = requestProduct(request, product);
            productService.updateProduct(product,pAdmin);
            json.setSuccess(true);
            json.setMsg("产品编辑成功...");
        } catch (Exception e) {
            logger.error("产品编辑失败",e);
            json.setMsg("产品编辑失败,数据库异常...");
        }
        return json;
    }

    @ResponseBody
    @RequestMapping("/productDel")
    @RequiresPermissions("product:product:del")
    public ResultJson productDel(@RequestParam("id") int id,HttpServletRequest request){
        ResultJson json = new ResultJson();
        try{
            productService.delProduct(id,request);
            json.setSuccess(true);
            json.setMsg("产品刪除成功...");
        }catch (Exception e) {
            logger.error("产品刪除失败,数据库异常...",e);
            json.setMsg("产品刪除失败,数据库异常...");
        }

        return json;

    }


    /**
     * 判断是否有文件上传
     * @param request
     * @param product
     * @return
     */
    private PProduct requestProduct(HttpServletRequest request, PProduct product) throws FileUploadException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断request是否有文件上传
        if(multipartResolver.isMultipart(request)){
            if (StringUtils.isNotEmpty(product.getFilepath())){
                String realPath = request.getSession().getServletContext().getRealPath(product.getFilepath());
                FileUtils.deleteQuietly(new File(realPath));
            }
            String fileNames[];
            fileNames = FileUploadUtils.saveFile((MultipartHttpServletRequest) request, "/product", new String[]{"jpg", "png", "gif", "jpeg", "bmp"});
            if(fileNames != null && fileNames.length == 1){
                product.setFilepath(fileNames[0]);
            }
        }
        return product;
    }



}
